<template>
  <el-dialog v-model="dialogVisible" title="用户登录 / 注册"  width="550px">
    <el-tabs v-model="activeTab">
      <!-- 登录 -->
      <el-tab-pane label="登录" name="login">
        <el-form ref="loginFormRef" label-position="right" :model="loginForm" :rules="loginRules" label-width="80px" >
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="loginForm.mobile" placeholder="请输入手机号" maxlength="15"></el-input>
          </el-form-item>
          <el-form-item label="密　码" prop="password">
            <el-input v-model="loginForm.password" type="password" show-password placeholder="请输入密码" maxlength="15"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleLogin">登录</el-button>
            <el-button @click="activeTab = 'forgotPassword'">忘记密码?</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 注册 -->
      <el-tab-pane label="注册" name="register">
        <el-form ref="registerFormRef" label-position="right" :model="registerForm" :rules="registerRules" label-width="80px">
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="registerForm.mobile" placeholder="请输入手机号" maxlength="15"></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input
              v-model="registerForm.code"
              placeholder="请输入验证码"
               maxlength="6"
              style="width: 60%; margin-right: 10px"
            ></el-input>
            <el-button type="primary" @click="sendRegisterCode" :disabled="registerCodeCountdown > 0">
              {{ registerCodeCountdown > 0 ? `${registerCodeCountdown}s` : '获取验证码' }}
            </el-button>
          </el-form-item>
          <el-form-item label="密　码" prop="password" >
            <el-input v-model="registerForm.password" type="password" placeholder="请设置密码" maxlength="15"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleRegister">注册</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 忘记密码 -->
      <el-tab-pane label="找回密码" label-position="right" name="forgotPassword">
        <el-form ref="forgotPasswordFormRef" :model="forgotPasswordForm" :rules="forgotPasswordRules" label-width="80px">
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="forgotPasswordForm.mobile" placeholder="请输入手机号" maxlength="15"></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input
              v-model="forgotPasswordForm.code"
              placeholder="请输入验证码"
              maxlength="6"
              style="width: 60%; margin-right: 10px"
            ></el-input>
            <el-button type="primary" @click="sendForgotPasswordCode" :disabled="forgotPasswordCodeCountdown > 0">
              {{ forgotPasswordCodeCountdown > 0 ? `${forgotPasswordCodeCountdown}s` : '获取验证码' }}
            </el-button>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="forgotPasswordForm.newPassword" type="password" show-password placeholder="请设置新密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleForgotPassword">重置密码</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script>
import { defineComponent, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/useStore'
import * as httpService from '@/services/apply.service'

export default defineComponent({
  setup(_, { expose }) {
    const userStore = useUserStore()
    const dialogVisible = ref(false)
    const activeTab = ref('login')

    // 登录表单
    const loginFormRef = ref(null)
    const loginForm = ref({ mobile: '', password: '' })
    const loginRules = {
      mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    }

    // 注册表单
    const registerFormRef = ref(null)
    const registerForm = ref({ mobile: '', code: '', password: '' })
    const registerCodeCountdown = ref(0)
    const registerRules = {
      mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
      code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
      password: [{ required: true, message: '请设置密码', trigger: 'blur' }],
    }

    // 忘记密码表单
    const forgotPasswordFormRef = ref(null)
    const forgotPasswordForm = ref({ mobile: '', code: '', newPassword: '' })
    const forgotPasswordCodeCountdown = ref(0)
    const forgotPasswordRules = {
      mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
      code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
      newPassword: [{ required: true, message: '请设置新密码', trigger: 'blur' }],
    }

    // 发送验证码
    const sendRegisterCode = async () => {
      if (!registerForm.value.mobile) return ElMessage.warning('请输入手机号')
      await httpService.sendRegisterCode({ mobile: registerForm.value.mobile })
      ElMessage.success('验证码已发送')
      startCountdown(registerCodeCountdown)
    }

    const sendForgotPasswordCode = async () => {
      if (!forgotPasswordForm.value.mobile) return ElMessage.warning('请输入手机号')
      await httpService.sendForgotPasswordCode({ mobile: forgotPasswordForm.value.mobile })
      ElMessage.success('验证码已发送')
      startCountdown(forgotPasswordCodeCountdown)
    }

    const startCountdown = (countdown) => {
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) clearInterval(timer)
      }, 1000)
    }

    // 登录
    const handleLogin = () => {
      loginFormRef.value.validate(async (valid) => {
        if (!valid) return
        // try {
        await userStore.userLogin(loginForm.value);
          // const res = await httpService.userLogin(loginForm.value)
          // userStore.authInfo = res
          // userStore.setAuthToken(res.authToken);
          ElMessage.success('登录成功')
          dialogVisible.value = false
        // } catch (error) {
        //   ElMessage.error(error.message)
        // }
      })
    }

    // 注册
    const handleRegister = () => {
      registerFormRef.value.validate(async (valid) => {
        if (!valid) return
        try {
          await httpService.userRegister(registerForm.value)
          ElMessage.success('注册成功，请登录')
          activeTab.value = 'login'
        } catch (error) {
          ElMessage.error(error.message)
        }
      })
    }

    // 找回密码
    const handleForgotPassword = () => {
      forgotPasswordFormRef.value.validate(async (valid) => {
        if (!valid) return
        try {
          await httpService.resetPassword(forgotPasswordForm.value)
          ElMessage.success('密码已重置，请重新登录')
          activeTab.value = 'login'
        } catch (error) {
          ElMessage.error(error.message)
        }
      })
    }

    // 打开弹窗
    const openDialog = () => {
      dialogVisible.value = true
    }

    expose({ openDialog })
    // 允许外部调用 openDialog 方法
    // defineExpose({ openDialog })

    return {
      openDialog,
      dialogVisible,
      activeTab,
      loginFormRef,
      loginForm,
      loginRules,
      handleLogin,
      registerFormRef,
      registerForm,
      registerRules,
      sendRegisterCode,
      registerCodeCountdown,
      handleRegister,
      forgotPasswordFormRef,
      forgotPasswordForm,
      forgotPasswordRules,
      sendForgotPasswordCode,
      forgotPasswordCodeCountdown,
      handleForgotPassword,
    }
  },
})
</script>
